using System.Linq;
using Microsoft.AspNetCore.Mvc;
using EFCoreBookStore.Models;
using System.Collections.Generic;

namespace EFCoreBookStore.Controllers
{
    public class BookController : Controller
    {

        [HttpGet]
        public IActionResult Index()
        {
            IList<BookViewModel> items = new List<BookViewModel>();
            BookStoreDataContext db = new BookStoreDataContext();
            var bookList = db.Books.ToList();

            foreach(Book book in bookList){
                BookViewModel item = new BookViewModel();

                item.ISBN = book.ISBN;
                item.Title = book.Title;
                item.Photo = book.Photo;
                item.PublishDate = book.PublishDate;
                item.Price = book.Price;
                item.Quantity = book.Quantity;
                var category = db.Categories.Where(p=>p.CategoryID.Equals(book.CategoryID)).Single<Category>();
                item.CategoryName = category.Name;

                string authorNameList = string.Empty;
                var booksAuthorsList = db.BooksAuthors.Where(p=>p.ISBN.Equals(book.ISBN));
                foreach(BookAuthor booksAuthors in booksAuthorsList){
                    BookStoreDataContext db2 = new BookStoreDataContext();
                    var author = db2.Authors.Where(p=>p.AuthorID.Equals(booksAuthors.AuthorID)).Single<Author>();
                    authorNameList = authorNameList + author.Name + ", ";
                }
                item.AuthorNames = authorNameList.Substring(0, authorNameList.Length - 2);

                items.Add(item);
            }

            return View(items);
        }
    }
}
